import Vue from 'vue'
import axiosBase from 'axios'
import qs from 'qs'
import {
  HTTP_SUCCESS,
  URL_PATH
} from '../config/config'

const axios = axiosBase.create({
  baseURL: URL_PATH,
  withCredentials: true
})
// axios.defaults.withCredentials = true
let vue = new Vue()

const common = {
  cus_id: ''
}

function relogin() {
  // localStorage.removeItem('userInfo')
  // vue.$nextTick(() => {
  //   vue.$router.push('/login')
  // })
}

function rejected(err) {
  if (err.message === 'Network Error') {
    vue.$message.error(err.message)
    relogin()
  }

  throw new Error(err)
}

function fulfilled(data) {
  if (data.data.state === HTTP_SUCCESS) {
    return data
  } else {
    return data
    // throw new Error(data.data.text)
  }
}

function post(url, params) {
  console.log(url + " --->  " + JSON.stringify(params));
  return axios.post(URL_PATH + url, encode(params, true)).then(fulfilled).catch(rejected)
}

// function upload(url, params) {
//   return axios.post(URL_PATH + url, uploadEncode(params)).then(fulfilled).catch(rejected)
// }

// function get(url, params) {
//   return axios.get(URL_PATH + url, { params: encode(params, false) }).then(fulfilled).catch(rejected)
// }

const api = {

  cache: (params) => post(`submit/submit/cache`, params), //缓存
  getCache: (params) => post(`submit/submit/getCache`, params), //获得缓存
  submitSubmission: (params) => post(`submit/submit/add`, params), //提交
  editor: (params) => post(`index/api/editor`, params), //获取编委列表
  getAisInfoById: (params) => post(`adminIndex/getAisInfoById`, params), //通过id获取用户信息
}

Object.defineProperty(api, '_setApp', {
  value(app) {
    vue = app
  }
})

export function encode(params, isPost) {
  common.cus_id = localStorage.getItem('cus_id')
  if (common.cus_id) {
    params = Object.assign({}, common, params)
  }
  params = isPost ? qs.stringify(params) : params

  return params
}

export function uploadEncode(params) {
  const cus_id = localStorage.getItem('cus_id')
  params.append('cus_id', cus_id)

  return params
}

export default api
